package com.dx.generator.controller;

import com.dx.generator.bean.ConfigDataEntity;
import com.dx.generator.service.SysGeneratorService;
import com.dx.generator.util.PageUtils;
import com.dx.generator.util.Query;
import com.dx.generator.util.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * Description: 代码生成器控制层
 *
 * @author rockstarsteve
 * @version 1.0
 * @copyright Copyright (c) 电信
 * @since 2023/9/7
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {

    @Autowired
    private SysGeneratorService sysGeneratorService;

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public Result list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));
        return Result.ok().put("page", pageUtil);
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(ConfigDataEntity configDataEntity, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1 设置输出文件的名称，中文转码
        BiFunction<SimpleDateFormat, Date, String> format = SimpleDateFormat::format;
        String fileName = "代码生成器生成的代码"
                + format.apply(new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"), new Date())
                + ".zip";
        // 2： 获得浏览器信息并转换为大写
        String agent = request.getHeader("User-Agent").toUpperCase();
        // 2.1：IE浏览器和Edge浏览器
        if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else { // 2.2:其他浏览器
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }

        byte[] data = sysGeneratorService.generatorCode(configDataEntity.getTables().split(","), configDataEntity);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

}
